<?php
	class CheckingController extends Controller {
		public function actionIndex() {
			$this->render('check');
		}
		
		public function actionCheck() {
			$book = Book::model()->findByAttributes(
				array('idbook' => $_POST['id'])
			);
			// if delete button is hit
			if (strtolower($_POST['order']) == 'delete') {
				BookGenre::model()->deleteAllByAttributes(
					array('idbook' => $_POST['id'])
				);
				unlink('resource/'.$book->name);
				if ($book->urlimage != 'Ebook Image') {
					unlink($book->urlimage);
				}
				$book->delete();
			} else { // if check button is hit
				// book name
				if ($_POST['book'] !== null && $_POST['book'] !== '') {
					rename('resource/'.$book->name, 'resource/'.$_POST['book']);
					$book->name = $_POST['book'];
				}
				// author
				$book->author = $_POST['author'];
				// book cover
				if ($_FILES['image']['name'] !== null) {
					if ($book->urlimage != 'Ebook Image') {
						unlink($book->urlimage);
					}
					move_uploaded_file(
						$_FILES['image']['tmp_name'],
						'imagebooks/'.$_FILES['image']['name']
					);
					$book->urlimage = 'imagebooks/'.$_FILES['image']['name'];
				}
				// book genres
				BookGenre::model()->deleteAllByAttributes(array('idbook' => $_POST['id']));
				if (isset($_POST['genreList'])) {
					foreach($_POST['genreList'] as $idgenre) {
						if ($idgenre == true) {
							$book_genre = new BookGenre();
							$book_genre->idgenre = $idgenre;
							$book_genre->idbook = $_POST['id'];
							$book_genre->save();
						}
					}
				}
				$book->idstaff = Yii::app()->user->id;
				$book->check = 2;
				$book->save();
			}
			$this->render('check');
		}
		
		public function filters() {
			return array(
				'accessControl'
			);
		}
		
		public function accessRules() {
				return array(
				array('allow',
					'users'=>array('@'),
				),
				array('deny',
					'users'=>array('*'),
				),
			);
		}
	}
?>